#include "StdAfx.h"
#include "fdmempoptstepcondition.h"

namespace QuantLib {

	 FdmEmpOptStepCondition::FdmEmpOptStepCondition(
		const Time &vestingStartTime,
		const Handle<YieldTermStructure>& employeeLossTS,
        const boost::shared_ptr<FdmMesher> & mesher,
		const boost::shared_ptr<FdmInnerValueCalculator> & calculator)
		: mesher_(mesher),
		  calculator_(calculator),
		  employeeLossRate_(employeeLossTS),
		  vestingStartTime_(vestingStartTime)
	 {
	 }

    void FdmEmpOptStepCondition::applyTo(Array& a, Time t) const 
	{
		if(t >= vestingStartTime())
		{
			Time dt = 0.0001;
			Time t1 = t + dt;
			Real instantEmpLoss = employeeLossRate()->forwardRate(t, t1, Continuous, NoFrequency, true) * dt;

			boost::shared_ptr<FdmLinearOpLayout> layout = mesher_->layout();
			const FdmLinearOpIterator endIter = layout->end();

			const Size dims = layout->dim().size();
			Array locations(dims);

			for (FdmLinearOpIterator iter = layout->begin(); iter != endIter;
				++iter) {
				for (Size i=0; i < dims; ++i)
					locations[i] = mesher_->location(iter, i);

				const Real innerValue = calculator_->innerValue(iter);
				a[iter.index()] += instantEmpLoss * innerValue;
			}
		}
    }
}